#!/bin/bash
. "$TONE_ROOT/lib/cpu_affinity.sh"
server_cmd="iperf3 --server --daemon"
readonly essh="ssh -o StrictHostKeyChecking=no"

[[ ! ${NUMACTL} ]] && glb_numa='numactl -C 0 -m 0' || glb_numa=${NUMACTL}

setup()
{

    export PATH="$TONE_BM_RUN_DIR"/bin:$PATH
    teardown

    firewalld_status_flag=0
    firewalld_status=`systemctl status firewalld`
    if [[ $firewalld_status =~ "active" ]];then
        systemctl stop firewalld
        firewalld_status_flag=1
    fi

    logfile=$(mktemp /tmp/iperf-server.log.XXXXXX)
    [ "$protocol" = "udp" ] && opt_udp=-u
    [ -n "$SERVER" ] && server=${SERVER%% *} || server="127.0.0.1"
    if [ "$server" = "127.0.0.1" ];then
        echo "$server ${glb_numa} $server_cmd"
        ${glb_numa} $server_cmd &> "$logfile"
    else
        echo "$essh $server ${glb_numa} $TONE_BM_RUN_DIR/bin/$server_cmd"
        $essh "$server" ${glb_numa} "$TONE_BM_RUN_DIR/bin/$server_cmd"
    fi
    
}

run()
{
    client_cmd="${glb_numa} iperf3 -t $runtime -f M -J -c $server $opt_udp"
    echo "${client_cmd}"
    ${client_cmd} | tee 2>&1 "$TONE_CURRENT_RESULT_DIR"/${testsuite}.json
    echo "client_cmd has finished"
}

parse()
{
    "$TONE_BM_SUITE_DIR"/parse.py
}

teardown()
{
    if [ "$server" = "127.0.0.1" ]; then
        pkill iperf &>/dev/null
    else
        ssh $server pkill -f iperf &>/dev/null
    fi

    rm -rf /tmp/iperf-server.log.*
    sleep 2
    if [ $firewalld_status_flag -eq 1 ];then
        systemctl start firewalld
    fi

}
